#include "model/data.h"
#include "choosefrienddialog.h"
#include "debug.h"

/*********************************
 * 选择好友窗口中的一个 元素/好友项
 ********************************/
ChooseFriendItem::ChooseFriendItem(const QString& userId,chooseFriendDialog *owner, const QIcon &avatar, const QString &name, bool checked)
    :owner(owner),userId(userId)
{
    // 1. 设置控件的基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    // 2. 设置布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(5);
    hlayout->setContentsMargins(10,0,10,0);
    this->setLayout(hlayout);

    // 3. 创建复选框
    checkBox = new QCheckBox();
    checkBox->setChecked(checked);
    checkBox->setFixedSize(25,25);
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 20px; height: 20px; image: url(:/resource/image/unchecked.png);}";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png);}";
    checkBox->setStyleSheet(style);

    // 4. 创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40,40);
    avatarBtn->setIconSize(QSize(40,40));
    avatarBtn->setIcon(avatar);

    // 5. 创建名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel {background-color: transparent;}");

    // 6. 添加上述内容到布局管理器中
    hlayout->addWidget(checkBox);
    hlayout->addWidget(avatarBtn);
    hlayout->addWidget(nameLabel);

    // 7. 连接信号槽
    connect(checkBox,&QCheckBox::toggled,this,[=](bool checked){
        if(checked)
        {
            // 勾选了复选框, 把当前这个 Item, 添加到右侧的已选择区域
            // owner->addSelectedFriend(this);
            owner->addSelectedFriend(userId,avatar,name,checked);
        }
        else
        {
            // 取消勾选
            owner->delSelectedFriend(userId);
        }
    });
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    // 根据鼠标的进入状态, 来决定绘制成不同的颜色
    QPainter painter(this);
    if(isHover)
    {
        // 绘制成深色
        painter.fillRect(this->rect(),QColor(230,230,230));
    }
    else {
        // 绘制成浅色
        painter.fillRect(this->rect(),QColor(255,255,255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void)event;
    isHover = true;
    // update 相当于 "更新界面"
    this->update();
    // 或者使用下列代码
    // this->repaint();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void)event;
    isHover = false;
    // update 相当于 "更新界面"
    this->update();
}

/*********************************
 * 选择好友窗口
 ********************************/

chooseFriendDialog::chooseFriendDialog(QWidget *parent)
    :QDialog(parent)
{
    // 1. 设置窗口的基本属性
    this->setFixedSize(700,550);
    this->setWindowFlag(Qt::WindowType::FramelessWindowHint);
    // 窗口被关闭时, 自动销毁这个对话框对象.
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QDialog { background-color: rgb(255, 255, 255);}");

    // 2. 创建布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(0);
    hlayout->setContentsMargins(0,0,0,0);
    this->setLayout(hlayout);

    // 3. 针对左侧窗口进行初始化
    initTotal(hlayout);

    // 4. 针对右侧窗口进行初始化
    initSelected(hlayout);
}

void chooseFriendDialog::initTotal(QHBoxLayout *layout)
{

    // 1. 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    // 设置滚动条相关的样式
    QString style = "QScrollBar:vertical {border: none;background: rgb(255,255,255);width: 10px;margin: 0px 0px 0px 0px;}\
        QScrollBar::handle:vertical {background: #c1c1c1;min-height: 20px;border-radius: 5px;}\
        QScrollBar::handle:vertical:hover {background: #a8a8a8;}\
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {height: 0px;}\
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none;}";
    scrollArea->verticalScrollBar()->setStyleSheet(style);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollArea { border:none; }");
    layout->addWidget(scrollArea,1);

    // 2. 创建 QWidget 设置到滚动区域中.
    totalContainer = new QWidget();
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(totalContainer);

    // 3. 创建左侧子窗口内部的 垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(10,10,0,10);
    vlayout->setAlignment(Qt::AlignTop);
    totalContainer->setLayout(vlayout);

    // 还需要进一步的添加 vlayout 内部的元素, 才能看到效果!
    // 此处也是先构造测试数据, 后续接入服务器之后, 从服务器拿到真实的好友列表, 再添加真实的数据
#ifdef TEST_UI
    QIcon defaultAvatar(":/resource/image/defaultAvatar.png");
    for(int i = 0;i < 30;++i)
    {
        this->addFriend(QString::number(100+i),defaultAvatar,"小短腿",false);
    }
#endif


}

void chooseFriendDialog::initSelected(QHBoxLayout *layout)
{
    // 1. 创建右侧的布局管理器
    QGridLayout* glayout = new QGridLayout();
    glayout->setSpacing(0);
    glayout->setContentsMargins(10,10,0,10);
    layout->addLayout(glayout,1);

    // 2. 创建 "提示" label
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700}");

    // 3. 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    // 设置滚动条相关的样式
    QString style = "QScrollBar:vertical {border: none;background: rgb(255,255,255);width: 10px;margin: 0px 0px 0px 0px;}\
        QScrollBar::handle:vertical {background: #c1c1c1;min-height: 20px;border-radius: 5px;}\
        QScrollBar::handle:vertical:hover {background: #a8a8a8;}\
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {height: 0px;}\
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none;}";
        scrollArea->verticalScrollBar()->setStyleSheet(style);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollArea { border:none; }");

    // 4. 创建滚动区域中的 QWidget
    selectedContainer = new QWidget();
    selectedContainer->setObjectName("selectedContainer");
    selectedContainer->setStyleSheet("#selectedContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(selectedContainer);

    // 5. 创建 selectedContainer 中的 "垂直布局"
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    selectedContainer->setLayout(vlayout);

    // 6. 创建底部按钮
    QString btnstyle = "QPushButton { color: rgb(7, 191, 96); background-color: rgb(240, 240, 240); border: none; border-radius: 5px;}";
    style += "QPushButton:hover { background-color: rgb(220, 220, 220); } QPushButton:pressed { background-color: rgb(200, 200, 200); }";

    QPushButton* okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(btnstyle);

    QPushButton* cancelBtn  = new QPushButton();
    cancelBtn ->setFixedHeight(40);
    cancelBtn ->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    cancelBtn ->setText("取消");
    cancelBtn ->setStyleSheet(btnstyle);

    // 7. 把上述控件添加到布局中
    glayout->addWidget(tipLabel,0,0,1,9);
    glayout->addWidget(scrollArea,1,0,1,9);
    glayout->addWidget(okBtn,2,1,1,3);
    glayout->addWidget(cancelBtn,2,5,1,3);

    // 构造一些数据用来进行测试界面
#if 0
    // 此处的数据通过勾选左侧列表来生成.
    QIcon icon(":/resource/image/defaultAvatar.png");
    for(int i = 0;i < 30;++i)
    {
        this->addSelectedFriend(QString::number(1000+i),icon,"小短腿",false);
    }
#endif

    // 8. 添加信号槽, 处理 ok 和 cancel 的点击
    // 完成按钮稍后处理
    connect(cancelBtn,&QPushButton::clicked,this,[=](){
        this->close();
    });
}

void chooseFriendDialog::addFriend(const QString &userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem* cfItem = new ChooseFriendItem(userId,this,avatar,name,checked);
    totalContainer->layout()->addWidget(cfItem);

}

void chooseFriendDialog::addSelectedFriend(const QString &userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem* cfItem = new ChooseFriendItem(userId,this,avatar,name,checked);
    selectedContainer->layout()->addWidget(cfItem);
}

void chooseFriendDialog::delSelectedFriend(const QString &userId)
{
    // 遍历 selectedContainer 中的每个 Item, 对比每个 Item 里的 userId , 是否是要删除的 userId.
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    // 由于是要 "遍历" + "删除" 需要从后往前进行
    LOG_DEBUG << vlayout->count() << "\n";
    for(int i = vlayout->count()-1;i >= 0;--i)
    {
        auto* item = vlayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr)
        {
            continue;
        }
        ChooseFriendItem* choosefriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        // 判定当前的 Item 的 userId 是否是要删除的 userId
        if(choosefriendItem->getUserId() != userId)
        {
            continue;
        }
        vlayout->removeWidget(choosefriendItem);
        // 此处直接使用 delete 可能导致程序直接崩溃. 因为 delete 该对象的时候, 该对象内部的 QCheckBox 还在使用中 (触发着信号槽呢)
        // 改成 deleteLater, 就相当于把 delete 操作委托给 Qt 自身来完成了. 告诉 Qt 框架说, 你要删除这个对象. 至于啥时候删除 Qt
        // 会确保在 Qt 自身用完了之后, 去真正删除.
        // delete chooseFriendItem;
        choosefriendItem->deleteLater();
    }

    QVBoxLayout* lvlayout = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    // 再遍历一下左侧列表, 把左侧列表中对应 item 的 checkBox 勾选状态取消掉.
    LOG_DEBUG << lvlayout->count() << "\n";
    for(int i = 0;i < lvlayout->count();++i)
    {
        auto* item = lvlayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr)
        {
            continue;
        }
        ChooseFriendItem* choosefriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(choosefriendItem->getUserId() != userId)
        {
            continue;
        }
        // 取消 checkBox 选中状态
        choosefriendItem->getCheckBox()->setChecked(false);
    }
}

void chooseFriendDialog::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);  // 抗锯齿

    // 绘制圆角矩形背景
    QPainterPath path;
    path.addRoundedRect(rect(), 15, 15);  // 圆角半径
    painter.fillPath(path, QColor("#F3F3F3"));
}

